package org.lim.lcpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.lim.lcpicturebackend.constant.PasswordConstant;
import org.lim.lcpicturebackend.exception.BusinessException;
import org.lim.lcpicturebackend.exception.ErrorCode;
import org.lim.lcpicturebackend.exception.ThrowUtils;
import org.lim.lcpicturebackend.manager.auth.StpKit;
import org.lim.lcpicturebackend.model.dto.user.UserLoginRequest;
import org.lim.lcpicturebackend.model.dto.user.UserQueryRequest;
import org.lim.lcpicturebackend.model.dto.user.UserRegisterRequest;
import org.lim.lcpicturebackend.model.entity.User;
import org.lim.lcpicturebackend.model.enums.UserRoleEnum;
import org.lim.lcpicturebackend.model.vo.user.LoginUserVO;
import org.lim.lcpicturebackend.model.vo.user.UserVO;
import org.lim.lcpicturebackend.service.UserService;
import org.lim.lcpicturebackend.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


import static org.lim.lcpicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author sk
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-05-17 19:50:29
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
/**
 * @Description:
 * @param userRegisterRequest 用户注册参数
 * @return long
 * @Author: lim
 * @Date: 2025/5/17 20:31
 */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        //1.校验参数
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if(StrUtil.hasBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if(userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入的密码不一致");
        }
        //2.检查用户账号和数据库中是否一致
       /* QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        Long count = this.baseMapper.selectCount(queryWrapper);*/
        long count = this.count(new QueryWrapper<User>().eq("userAccount",userAccount));
        /*if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }*/
        ThrowUtils.throwIf(count > 0,ErrorCode.PARAMS_ERROR,"账号重复");
        //3.密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        //4.插入数据到数据库中
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserName("昵称无");
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult,ErrorCode.SYSTEM_ERROR,"注册失败，保存数据失败");
        return user.getId();
    }
    /**
     * 获取加密密码
     * @param userPassword 用户密码
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword){
        //加盐，混淆密码
         /*PasswordConstant.SALT*/
        return DigestUtils.md5DigestAsHex((PasswordConstant.SALT + userPassword).getBytes());
    }
 /**
  *
  * @param userLoginRequest 请求参数
  * @param request servlet request
  * @return 脱敏LoginUserVo
  * @Author: lim
  * @Date: 2025/5/17 21:24
  */

    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1.校验
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空为空");
        }
        if(userAccount.length() < 4 || userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名不能小于4位或密码不能小于8位");
        }

        //2.对用户传递的密码加密
        userPassword = getEncryptPassword(userPassword);
        //3.查询数据库中的用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", userPassword);
        User user = this.getOne(queryWrapper);

        //不存在抛异常
        if(ObjUtil.isEmpty(user)){
            log.info("user login fail, user not exist or password or userAccount not match ");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或者密码错误");
        }
//        4.保存用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);

        //
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);

        return this.getLoginUserVo(user);


    }
    /**
     * 用户视图转换
     * @param user 用户信息
     * @return
     */

    @Override
    public LoginUserVO getLoginUserVo(User user) {
        if(user == null){
            return null;
        }
        LoginUserVO loginUserVo = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVo);
        return loginUserVo;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }
//@Override
//public User getLoginUser() { // 移除了 HttpServletRequest 参数
//    // 1. 从 ThreadLocal 中获取当前登录用户的 ID
//    Long userId = BaseContext.getCurrentId();
//
//    // 2. 校验用户 ID 是否存在
//    if (userId == null) {
//        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
//    }
//
//    // 3. 从数据库查询用户信息
//    User currentUser = this.getById(userId);
//    if (currentUser == null) {
//        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户不存在或已被删除");
//    }
//
//    return currentUser;
//}
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未登录");
        }
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;

    }
//    @Override
//    public boolean userLogout() {
//        // 判断是否已经登录
//        Long currentId = BaseContext.getCurrentId();
//        if (currentId == null) {
//            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未登录");
//        }
//        //移除登录态
////        request.getSession().removeAttribute(USER_LOGIN_STATE);
//        BaseContext.removeCurrentId();
//        return true;
//
//    }

    /**
     * 获取脱敏后的用户数据
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户数据列表
     */

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
    @Override
    public Page<UserVO> convertToUserVOPage(Page<User> userPage) {
        Page<UserVO> userVOPage = new Page<>(
                userPage.getCurrent(),
                userPage.getSize(),
                userPage.getTotal()
        );

        // Only convert records if there are any to avoid unnecessary processing
        if (CollectionUtils.isNotEmpty(userPage.getRecords())) {
            userVOPage.setRecords(this.getUserVOList(userPage.getRecords()));
        } else {
            userVOPage.setRecords(Collections.emptyList());
        }

        return userVOPage;
    }
    @Override
    public Page<User> pageUsers(long current, long pageSize, UserQueryRequest userQueryRequest) {
        // 确保正确的分页参数
        current = Math.max(current, 1);
        pageSize = Math.max(Math.min(pageSize, 100), 1); // Prevent excessive page sizes

        // 根据请求条件构建查询参数
        QueryWrapper<User> queryWrapper = getQueryWrapper(userQueryRequest);

        // 执行分页查询
        return this.page(new Page<>(current, pageSize, true), queryWrapper);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


}




